<template>
	<view class="container">
		<u-form :model="form" ref="uForm" label-position="top" :label-width="130">
			<u-form-item label="旧密码" prop="oldPassword">
				<u-input v-model="form.oldPassword" placeholder="请输入旧密码" type="password" />
			</u-form-item>
			<u-form-item label="新密码" prop="newPassword">
				<u-input v-model="form.newPassword" placeholder="请输入新密码" type="password"/>
			</u-form-item>
			<u-form-item label="确认密码" prop="confirmPassword">
				<u-input v-model="form.confirmPassword" placeholder="请确认新密码" type="password"/>
			</u-form-item>

			<u-button class="action" @click="commitClick">确认</u-button>
		</u-form>
	</view>
</template>

<script>
	import md5 from "@/utils/md5.js";
	import {
		modifyPassword
	} from '@/api/user.js'
	export default {
		data() {
			return {
				form: {
					oldPassword: '',
					newPassword: '',
					confirmPassword: ''
				},
				rules: {
					oldPassword: [{
						required: true,
						message: '请输入旧密码',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change'],
					}],
					newPassword: [{
						required: true,
						message: '请输入新密码',
						trigger: ['change'],
					}],
					confirmPassword: [{
						required: true,
						message: '请确认新密码',
						trigger: ['change'],
					}],
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			commitClick() {
				console.log('commitClick');
				this.$refs.uForm.validate(valid => {
					if (valid) {
						if (this.form.newPassword !== this.form.confirmPassword) {
							this.$u.toast('两次新密码不相同，请重新输入')
							return
						}
						this.modify();
					}
				});
			},

			modify() {
				
				const oldPassword = md5.hex_md5(this.form.oldPassword)
				const newPassword = md5.hex_md5(this.form.newPassword)
				const confirmPassword = md5.hex_md5(this.form.confirmPassword)
				uni.showLoading({})
				modifyPassword({ oldPassword, newPassword, confirmPassword}).then(res => {
					console.log(res);
					uni.hideLoading();
					uni.showToast({
						icon: 'none',
						title: '密码修改成功',
						success() {
							uni.navigateBack({})
						}
					})
				})
			}
		}
	}
</script>
<style lang="scss">
	page {
		background-color: $app-page-bg-color;
	}
</style>
<style lang="scss">
	@import '@/css/u-form.scss';
	.container {
		padding-left: 40rpx;
		padding-right: 40rpx;
	}

	.action {
		margin-top: 60rpx;
	}
</style>
